import 'package:dio/dio.dart';

import 'component/TopicUi.dart';
import 'main.dart';

const baseUrl = "http://117.72.107.9:3000";
final dio = Dio(BaseOptions(baseUrl: baseUrl));

var globalServie = NetworkService();

class SongDesc {
  int duration;
  String sourceUrl;

  SongDesc(this.duration, this.sourceUrl);
}

class NetworkService {
  Future<SongDesc> songUrl(int songId) async {
    var r = await dio.get('/song/url?id=$songId');
    int total = r.data['data'][0]['time'] as int;
    String sourceUrl = r.data['data'][0]['url'];
    return SongDesc(total, sourceUrl);
  }

  Future<List<PlayItem>> playDetail(int playId) async {
    var response = await dio.get('/playlist/detail?id=$playId');
    List<dynamic> dynamicList =
        response.data['playlist']['tracks'] as List<dynamic>;
    int a = 0;
    List<PlayItem> t = dynamicList.map((e) {
      int id = e['id'] as int;
      String name = e['name'] as String;
      String imageUrl = e['al']['picUrl'];
      return PlayItem(
          id: id, name: name, imageUrl: imageUrl, duration: 0, index: a++);
    }).toList();
    return t;
  }

  Future<String> lyric(int songId) async {
    Response r = await dio.get('/lyric?id=$songId');
    return r.data['lrc']['lyric'];
  }

  Future<List<Topic>> playlist(String url) async {
    var r = await dio.get(url);
    var listdata = r.data['playlists'] as List<dynamic>;
    List<Topic> topicList = listdata.map((e) {
      String name = e['name'];
      String coverImgUrl = e['coverImgUrl'];
      int id = e['id'];
      return Topic(topicName: name, topicPicUrl: coverImgUrl, playId: id);
    }).toList();
    return topicList;
  }

  Future<List<PlayItem>> recommend() async {
    Response r = await dio.get(
      'http://117.72.107.9:8080/recommend',
    );
    print(r.data);
    List<dynamic> l = r.data['data']['dailySongs'];
    int a = 0;
    List<PlayItem> items = l.map((item) {
      int id = item['id'];
      String name = item['name'];
      String imageUrl = '';
      if (item['al'] != null && item['al']['picUrl'] != null) {
        imageUrl = '${item['al']['picUrl']}';
      }
      return PlayItem(
          id: id, name: name, imageUrl: imageUrl, duration: -1, index: a++);
    }).toList();
    return items;
  }
}
